package cn.wolfcode.luowowo.listener;

import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.redis.service.IStrategyStatisVORedisService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.vo.StrategyStatisVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.awt.print.Pageable;
import java.util.List;

//自定义监听器类(交给容器管理)
//继承ApplicationListener<ContextRefreshedEvent(监听事件之容器启动好后)>
@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IStrategyStatisVORedisService voRedisService;

    //完成逻辑操作
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.err.println("开始");
        //获取数据库内容
        List<Strategy> strategyList = strategyService.allList();
        //遍历每个攻略
        for (Strategy s : strategyList) {
            //如果数据已经存在缓存中则跳过这条
            if (voRedisService.hasStrategyStatisVO(s.getId())){
                continue;
            }
            //创建统计数据对象
            StrategyStatisVO vo = new StrategyStatisVO();
            //同步数据
            BeanUtils.copyProperties(s , vo);
            vo.setStrategyId(s.getId());
            //保存到redis中
            voRedisService.set(vo);
        }
        System.err.println("结束");
    }
}
